<!-- WebSocketChat.vue -->
<template>
  <div class="chat-container">
    <h2>WebSocket 连接测试</h2>
    <div class="input-group">
      <label for="userId">用户ID：</label>
      <input type="text" v-model="userId" placeholder="输入用户ID">
      <button @click="connect" :disabled="isConnected">连接</button>
      <button @click="disconnect" :disabled="!isConnected">断开</button>
    </div>
    <div class="input-group">
      <label for="targetId">目标用户ID：</label>
      <input type="text" v-model="targetId" placeholder="输入目标用户ID">
    </div>
    <div class="input-group">
      <label for="message">消息：</label>
      <input type="text" v-model="message" placeholder="输入消息" @keyup.enter="sendMessage">
      <button @click="sendMessage" :disabled="!isConnected">发送</button>
    </div>
    <div class="message-box" ref="messageBox">
      <div v-for="(msg, index) in messages" :key="index" class="message-item">
        {{ msg.sender }}: {{ msg.content }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'WebSocketChat',
  data() {
    return {
      ws: null,
      userId: '',
      targetId: '',
      message: '',
      messages: [],
      isConnected: false,
      heartbeatInterval: null
    }
  },
  methods: {
    connect() {
      if (!this.userId) {
        this.$message ? this.$message.warning('请输入用户ID') : alert('请输入用户ID');
        return;
      }

      // 连接到WebSocket服务器
      this.ws = new WebSocket(`ws://localhost:9228/${this.userId}`);

      this.ws.onopen = () => {
        this.isConnected = true;
        this.addMessage('系统', '已连接到服务器');
        // 启动心跳
        this.heartbeatInterval = setInterval(() => {
          if (this.ws && this.ws.readyState === WebSocket.OPEN) {
            this.ws.send('心跳');
          }
        }, 30000);
      };

      this.ws.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.addMessage(data.from, JSON.stringify(data));
        } catch (e) {
          // 心跳包不处理
          if (event.data !== '心跳') {
            this.addMessage('系统', event.data);
          }
        }
      };

      this.ws.onclose = () => {
        this.isConnected = false;
        this.addMessage('系统', '连接已断开');
        if (this.heartbeatInterval) {
          clearInterval(this.heartbeatInterval);
        }
      };

      this.ws.onerror = (error) => {
        this.isConnected = false;
        this.addMessage('系统', '连接错误: ' + error.message);
      };
    },

    disconnect() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
        this.isConnected = false;
        if (this.heartbeatInterval) {
          clearInterval(this.heartbeatInterval);
        }
      }
    },

    sendMessage() {
      if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
        this.$message ? this.$message.warning('请先连接到服务器') : alert('请先连接到服务器');
        return;
      }

      if (!this.targetId || !this.message) {
        this.$message ? this.$message.warning('请输入目标用户ID和消息') : alert('请输入目标用户ID和消息');
        return;
      }

      const data = {
        type: 'message',
        from: this.userId,
        to: this.targetId,
        content: this.message
      };

      this.ws.send(JSON.stringify(data));
      this.addMessage('我', `发送给 ${this.targetId}: ${this.message}`);
      this.message = '';
    },

    addMessage(sender, content) {
      this.messages.push({ sender, content });
      this.$nextTick(() => {
        if (this.$refs.messageBox) {
          this.$refs.messageBox.scrollTop = this.$refs.messageBox.scrollHeight;
        }
      });
    }
  },
  beforeDestroy() {
    this.disconnect();
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.input-group {
  margin: 15px 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.input-group input {
  flex: 1;
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.input-group button {
  padding: 8px 15px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-group button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.message-box {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  height: 300px;
  overflow-y: auto;
}

.message-item {
  margin: 5px 0;
  padding: 5px;
  border-bottom: 1px solid #ebeef5;
}
</style> 